import { App, Spin } from 'antd'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import { useEffect, useMemo } from 'react'
import ReactDOM from 'react-dom/client'
import { Provider } from 'react-redux'
import { RouterProvider } from 'react-router-dom'
import { YmAliOssFilePathRuleProvider, YmConfigProvider } from 'ym-design'
import { request } from './api/request'
import { YmEmbedBossAliOssConfig } from './common'
import './globalStyles/main.less'
import { store } from './redux/store'
import { basicRouter } from './routers/routerConfig'
dayjs.locale('zh-cn')

function parseFromUrl() {
  // ?token=Msrqv...0ptB73Q-KhUSDYA&gowhere=waitlisting/package
  // 读取到了参数
  if (process.env.processEnvDetail.NODE_ENV === 'development') {
    // localStorage.setItem('insert-boss-token', '123');
    if (localStorage.getItem('insert-boss-token')) {
      localStorage.removeItem('insert-boss-token')
    }
    request.interceptors.request.use((config) => {
      const tk =
        'eyJjbGllbnRJZCI6ImNsaWVudElkIiwidHlwIjoiSldUIiwiYWxnIjoiSFMyNTYifQ.eyJ1c2VySW5mbyI6IntcInBob25lXCI6XCIxODY1ODg4ODg4MVwiLFwibG9naW5OYW1lXCI6XCJhZG1pblwiLFwidXNlck5hbWVcIjpcIui_kOiEieeuoeeQhuWRmFwifSIsImV4cCI6MTcwNTY1NzcwMywiaWF0IjoxNzA1NTcxMzAzfQ.MUagj2sTQkGx4Vd3uw4C3_obvyjrJWUM5BmjZdrQGvs.eyJ1c2VySW5mbyI6IntcInBob25lXCI6XCIxODY1ODg4ODg4MVwiLFwibG9naW5OYW1lXCI6XCJhZG1pblwiLFwidXNlck5hbWVcIjpcIui_kOiEieeuoeeQhuWRmFwifSIsImV4cCI6MTcwNTQ4MjIyOSwiaWF0IjoxNzA1Mzk1ODI5fQ.FVustNmR4bBJGMo_epvTTJ_ygrS4YR-BTPyuSIkL1v0'
      config.headers['Bosstk'] = tk
      //其他业务boss端token
      config.headers['ClientType'] = 'boss'
      return config
    })
  } else {
    if (window.location.search) {
      const usp = new URLSearchParams(window.location.search)
      const gowhere = usp.get('gowhere')
      const token = usp.get('token')
      // console.log('--嵌入token--gowhere--', token, gowhere);
      if (gowhere && token) {
        if (!localStorage.getItem('insert-boss-token')) {
          localStorage.setItem('insert-boss-token', token)
        }
        basicRouter.navigate(gowhere)
        request.interceptors.request.use((config) => {
          config.headers['Authorization'] = token
          return config
        })
      }
    }
  }
}

parseFromUrl()

function MyInit() {
  const { message } = App.useApp()

  useEffect(() => {
    const id = request.interceptors.response.use(
      function (response) {
        // console.log('--response--成功了就会走这里--');
        return response
      },
      (err: unknown) => {
        console.error('--response检查一下报错内容--', err)
        message.error(String(err).replace('AxiosError:', ''))
      }
    )
    return () => {
      request.interceptors.response.eject(id)
    }
  }, [message])

  return <></>
}

function AliProvider(props: { children: React.ReactNode }) {
  const value = useMemo(() => {
    return { ...YmEmbedBossAliOssConfig }
  }, [])

  return (
    <YmAliOssFilePathRuleProvider
      value={{ ...value, phone: store.getState().loginUser.mobile || '' }}
    >
      {props.children}
    </YmAliOssFilePathRuleProvider>
  )
}

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement)

root.render(
  <YmConfigProvider
    input={{ autoComplete: 'off' }}
    theme={{ token: { colorPrimary: '#3E84E9' } }}
  >
    <App>
      <Provider store={store}>
        <AliProvider>
          <MyInit />
          <RouterProvider router={basicRouter} fallbackElement={<Spin />} />
        </AliProvider>
      </Provider>
    </App>
  </YmConfigProvider>
)

// 开启热更新，否则页面内容改变，会刷新整个页面
// @ts-ignore
if (module.hot) {
  // @ts-ignore
  module.hot.accept((err) => {
    if (err) {
      console.error('module.hot, ', err)
    }
  })
}
